package javacommon.authority.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javacommon.authority.model.Org;
import javacommon.authority.model.Role;
import javacommon.authority.model.User;
import javacommon.authority.model.UserOrg;
import javacommon.authority.model.UserRole;
import javacommon.authority.validator.UserUpdateValidator;
import javacommon.kit.SecureKit;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.EncryptionKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class UserController extends Controller {
	public void list() {
		String para0 = getPara(0);
		Integer pageIndex = getParaToInt("pageIndex");
		Page<User> page = User.dao.findByPage(pageIndex);
		setAttr("status", "success");
		setAttr("page", page);
		// json请求
		if (para0 != null && para0.equals("json")) {
			renderJson();
		} else {// 非json请求
			render("userList.html");
		}
	}



	public void look() {
		String para0 = getPara(0);
		String id = getPara("id");
		if (StringUtils.isBlank(id)) {
			setAttr("status", "error");
		} else {
			User user = User.dao.findById(id);
			// 查找对应部门
			List<Org> userOrgs = Org.dao
					.findByUserId(id);
			user.put("userOrgs", userOrgs);
			List<Role> userRoles = Role.dao
					.findByUserId(id);
			user.put("userRoles", userRoles);
			setAttr("data", user);
			setAttr("status", "success");
		}
		// 请求json
		if (para0 != null && para0.equals("json")) {
			renderJson();
		} else {
			render("userLook.html");
		}
	}
//	@Before(UserUpdateValidator.class)
	public void update() {
		User user = getModel(User.class);
		String userId = user.get("id");
		String password = user.get("password");

		if (StringUtils.isBlank(password)) {
			user.set("password", null);
		} else {
			user.set("password", EncryptionKit.md5Encrypt(password));
		}


		if (StringUtils.isBlank(userId)) {//没有id，新增
			user.set("id", SecureKit.getUUID());
			user.save();//执行保存
			userId = user.getStr("id");
		} else {
			//如果是更新，但是表单提交密码为空，则需要保证原密码没有被改变
			User old_user = User.dao.findById(userId);
			if (StringUtils.isBlank(password)) {
				user.set("password", old_user.get("password"));
			}
			user.update();
			//如果是更新，先删除用户关联的部门信息和角色信息
			deleteOrgs(user);
			deleteRoles(user);
		}
		// 处理部门
		String str_orgIds = getPara("orgIds");
		String[] orgIds = null;

		if (StringUtils.isNotBlank(str_orgIds)) {
			orgIds = str_orgIds.split(",");
		}
		if (orgIds != null && orgIds.length > 0) {
			for (String orgId : orgIds) {// 每个部门id
				if (StringUtils.isBlank(orgId)) {
					continue;
				}
				UserOrg userOrg = new UserOrg();
				userOrg.set("id", SecureKit.getUUID()).set("userId", userId)
						.set("orgId", orgId).save();
			}
		}
		
		// 处理角色
		String[] roleIds = getParaValues("roleIds");
		if (roleIds != null && roleIds.length > 0) {
			for (String roleId : roleIds) {
				if (StringUtils.isBlank(roleId)) {
					continue;
				}
				UserRole userRole = new UserRole();
				userRole.set("id", SecureKit.getUUID()).set("userId", userId).set("roleId", roleId).save();
			}
		}
		setAttr("message", getText("update_success"));
		setAttr("status", "success");
		renderJson();
	}
	public void delete(){
		String id = getPara("id");
		User user = User.dao.findById(id);
		deleteRoles(user);
		deleteOrgs(user);
		user.delete();
		setAttr("status", "success");
		setAttr("message", getText("delete_success"));
		renderJson();
	}

	/**
	 * 删除用户-角色关联信息
	 * @param user
	 */
	private void deleteOrgs(User user) {
		List<UserOrg> orgs = user.getOrgs();
		for (UserOrg userOrg : orgs) {
			userOrg.delete();
		}
		
	}
	/**
	 * 删除用户-部门关联信息
	 * @param user
	 */
	private void deleteRoles(User user) {
		List<UserRole> roles = user.getRoles();
		for (UserRole userRole : roles) {
			userRole.delete();
		}
		
	}
}
